/**
 * 
 */
package com.gmail.blackdog1987.carcare.network.response.handler;

import org.apache.http.Header;
import org.json.JSONObject;

import com.gmail.blackdog1987.carcare.entity.TUser;
import com.gmail.blackdog1987.carcare.network.ResponseCustomError;
import com.gmail.blackdog1987.carcare.network.response.IResponse;
import com.gmail.blackdog1987.carcare.network.response.RegResponse;
import com.gmail.blackdog1987.carcare.util.LogUtil;
import com.google.gson.Gson;

/**
 * @author wdy
 *
 */
public class RegResponseHandler extends BaseResponseHandler {

	public static final String TAG = RegResponseHandler.class.toString();
	/** 监听类 */
	private OnResponseListener mListener;
	
	private RegResponse mResponse;
	
	public void setOnResponseListener(OnResponseListener l) {
		this.mListener = l;
	}

	@Override
	public void onFailure(int statusCode, Header[] headers,
			String responseString, Throwable throwable) {
		// TODO Auto-generated method stub
		super.onFailure(statusCode, headers, responseString, throwable);
		

		mResponse = new RegResponse();
		if(!checkConn(throwable)) {
			mResponse.error = IResponseHandler.CONNECTION_ERROR;
		} else {
			if(responseString != null) {
				LogUtil.e(TAG, responseString);
				mResponse.error = new ResponseCustomError(responseString);
			} else {
				LogUtil.e(TAG, responseString);
				mResponse.error = IResponseHandler.CONNECTION_ERROR;
			}
		}
		
		if(mListener != null) {
			mListener.onError(this);
		}
	
		
	}
	
	@Override
	public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
		// TODO Auto-generated method stub
		super.onSuccess(statusCode, headers, response);
		

		boolean result = this.parseJson(response);
		if(mListener == null) {
			return;
		}
		
		if(!result) {
			mListener.onError(this);
		} else {
			mListener.onResponse(this);
		}
	
	}
	
	public boolean parseJson(Object response) {
		mResponse = new RegResponse();
		try {
			if(response != null) {
				LogUtil.d(RegResponseHandler.class.toString(), response.toString());
				// 错误信息处理
				JSONObject json = (JSONObject)response;
				if(!(Boolean) json.get("success")) {
					mResponse.error = new ResponseCustomError(json.toString());
					return false;
				}
				JSONObject record = json.optJSONObject("record");
				mResponse.user = new TUser();
				mResponse.user = new Gson().fromJson(record.toString(), TUser.class); 
			}
		} catch (Exception e) {
			LogUtil.e(RegResponseHandler.class.toString(), e.getMessage());
			mResponse.error = IResponseHandler.JSON_PARSE_ERROR;
			if(checkWLAN(response)) {
				mResponse.error = IResponseHandler.CONNECTION_ERROR;
			}
		}
		return true;
	}

	@Override
	public IResponse getResponse() {
		return this.mResponse;
	}
}
